﻿<?php
/**
 * @Author: Zhao Yang[873777808@qq.com]
 * @Date:   2015-01-06 15:13:56
 * @Last Modified time: 2015-11-25 06:16:09
 */
function P($var)
{
	header('Content-type:text/html; charset=utf8');
	echo "<pre>";
	print_r($var);
	echo "</pre>";
}


function is_login(){
    $user = session('home_user');
    if (empty($user)) {
     return 0;
    } else {
     return session('home_user_sign') == data_auth_sign($user) ? $user['uid'] : 0;
    }
}

// 加密函数
function enKey()
{
   return substr(md5(C("KEY") . mt_rand(1, 1000) . C('KEY')), 0, 10);  
}

/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function data_auth_sign($data) {
    //数据类型检测
    if(!is_array($data)){
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}

// 无限级分类
function genTree($items, $id = 'id', $pid = 'pid', $son = 'son') 
{
		$tree = array();
		//格式化的树
		$tmpMap = array();
		//临时扁平数据
		foreach ($items as $item) {
			$tmpMap[$item[$id]] = $item;
		}
		foreach ($items as $item) {
			if (isset($tmpMap[$item[$pid]])) {
				$tmpMap[$item[$pid]][$son][$item[$id]] = &$tmpMap[$item[$id]];
			} else {
				$tree[$item[$id]] = &$tmpMap[$item[$id]];
			}
		}
		return $tree;
}

/**
 * 查询所有父级
 * @param  [type] $arr [description]
 * @param  [type] $id  [description]
 * @param  [type] $pid [description]
 * @return [type]      [description]
 */
function familytree($arr,$id,$idname='id',$pidname = 'pid') {
    $tree = array();
    foreach($arr as $v) {
        if($v[$idname] == $id) {// 判断要不要找父栏目
            if($v[$pidname] > 0) { // parnet>0,说明有父栏目
                $tree = array_merge($tree,familytree($arr,$v[$pidname],$idname,$pidname));
            }
            $tree[] = $v; // 以找到上地为例
        }
    }
    return $tree;
}

// 查询子级
function soncate($arr,$id,$pidname='pid'){
	$tmp = array();
	foreach ($arr as $key => $value) {
		if($value[$pidname] == $id)
			$tmp[]=$value;
	}
	return $tmp?$tmp:soncate($arr,$arr[$id][$pidname]);
}

/**
 * 获得子孙集ID
 * @param  [type] &$cate [description]
 * @param  [type] $pid   [description]
 * @return [type]        [description]
 */
function getChild(&$cate , $pid,$idname='id',$pidname='pid'){
		$arr = array();
		foreach ($cate as $k => $v) {
		   if ($v[$pidname] == $pid) {
		       $arr[] = $v[$idname];
		       unset($cate[$k]);
		       $arr = array_merge(getChild($cate,$v[$idname]),$arr);
		   }
		}
		return $arr;
}

/**
 * 删除文件夹目录
 * @param  [type] $dirname [description]
 * @return [type]          [description]
 */
function deldir($dirname){
	if(!is_dir($dirname))return;
	//$dirname=rtrim(str_replace('\\', '/', $dirname),'/').'/';
	foreach (glob($dirname.'\*') as  $file) {
		is_dir($file)?deldir($file):unlink($file);
	}
	rmdir($dirname);
}

function delFile($path)
{
    if(!is_dir($path)) return;
    foreach (glob($path.'\*') as  $file) {
        is_file($file)&&unlink($file);
    }
}


/**
 * 格式化数据为一维数组添加 level
 * @param  [type]  $categorys [description]
 * @param  integer $catId     [description]
 * @param  integer $level     [description]
 * @return [type]             [description]
 */
function getSubs($categorys,$catId=0,$level=0){
    $subs=array();  
    foreach($categorys as $item){  
        if($item['pid']==$catId){
            $item['level']=$level;
            $subs[]=$item;
            $subs=array_merge($subs,getSubs($categorys,$item['cid'],$level+1));
        }
              
    }  
    return $subs;  
} 

/**
 * 验证码检测
 */
function checkCode($code, $id = '')
{
	$verify = new \Think\Verify(); 
	return $verify->check($code, $id);
}



/**
 * 参数1---目标邮箱, 参数2----邮件标题,参数三--邮件正文,参数四---发件人名称;
 */
function SendMail($address, $title, $message, $fromname = 'NONE') {
    $mail = new \Custom\Mail();
    $mail->IsSMTP();
    $mail->Port = C('MAIL_PORT');
    $mail->CharSet = C('MAIL_CHARSET');
    $mail->AddAddress($address);
    $mail->Body = $message;
    $mail->From = C('MAIL_ADDRESS');
    $mail->FromName = $fromname;
    $mail->Subject = $title;
    $mail->Host = C('MAIL_SMTP');
    $mail->SMTPAuth = C('MAIL_AUTH');
    $mail->Username = C('MAIL_LOGINNAME');
    $mail->Password = C('MAIL_PASSWORD');
    $mail->IsHTML(C('MAIL_HTML'));
    return ($mail->Send());
}


function genTree5($items,$id='id',$pid='pid') { 
    foreach ($items as $item) 
        $items[$item[$pid]]['son'][$item[$id]] = &$items[$item[$id]]; 
    return isset($items[0]['son']) ? $items[0]['son'] : array(); 
}


function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

// 锁解决高并发问题
function startLock($file)
{
    $fp = fopen(COMMON_PATH.$file, 'r');
    if(!$fp)
        return FALSE;
    $try = 10;
    $lock = false;
    do 
    {
        $lock = flock($fp, LOCK_EX);
        if(!$lock)
            usleep(50000);  // 0.05秒
    }while(!$lock && --$try > 0);
    return $lock;
}

// 解锁
function endLock($file)
{
    if(is_file(COMMON_PATH.$file))
    {
        @flock(COMMON_PATH.$file, LOCK_UN);
        @fclose(COMMON_PATH.$file);
    }
}


